package yns.springcloud.oakwood.guide;

import java.util.Optional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.config.server.EnableConfigServer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;


// Git

//SpringCloudGuideConfigServer1  http://localhost:9500

// 更新对应的配置后，需要访问客户端的刷新接口刷新对应的配置，访问刷新命令：curl -X POST http://localhost:9510/actuator/refresh
//  可以添加消息总线做自动刷新，也可以根据需要手动刷新

// Client端的config配置需要放在bootstrap.properties文件中

// Git会下载整个库，建议配置文件根据项目单独建立新的Git库

//  配置文件读取格式:
//  /{application}/{profile}[/{label}]
//  /{application}-{profile}.yml
//  /{label}/{application}-{profile}.yml
//  /{application}-{profile}.properties
//  /{label}/{application}-{profile}.properties
//   application一般为主文件名，profile为指定环境，lablel为对应的版本(Git中表示分支)

@EnableConfigServer
@EnableDiscoveryClient   // 不想注册可以添加设置设置: eureka.client.enabled=false
@SpringBootApplication
public class SpringCloudSetup {
	
	private static final Logger logger = LoggerFactory.getLogger(SpringCloudSetup.class);

	private static final String SPRING_APPLICATION_NAME = "spring.application.name";
	private static final String SERVER_HOSTNAME = "server.hostname";
	private static final String SERVER_PORT = "server.port";
	private static final String EUREKA_CLIENT_SERVICEURL_DEFAULTZONE = "eureka.client.serviceUrl.defaultZone";

	private static final String DEFAULT_MESSAGE = "Does Key exist or null ?";

	public static void main(String[] args) throws Exception {
		ConfigurableApplicationContext configurableApplicationContext = SpringApplication.run(SpringCloudSetup.class,
				args);
		Environment environment = configurableApplicationContext.getEnvironment();

		logEnvironment(environment);
	}

	private static void logEnvironment(Environment environment) {
		Object[] objects = new Object[4];
		String format = "Environment Configure : \n" 
				+ "spring.application.name : {} \n" 
				+ "server.hostname : {} \n"
				+ "server.port : {} \n" 
				+ "eureka.client.serviceUrl.defaultZone : {} \n";

		objects[0] = Optional.ofNullable(environment.getProperty(SPRING_APPLICATION_NAME)).orElse(DEFAULT_MESSAGE);
		objects[1] = Optional.ofNullable(environment.getProperty(SERVER_HOSTNAME)).orElse(DEFAULT_MESSAGE);
		objects[2] = Optional.ofNullable(environment.getProperty(SERVER_PORT)).orElse(DEFAULT_MESSAGE);
		objects[3] = Optional.ofNullable(environment.getProperty(EUREKA_CLIENT_SERVICEURL_DEFAULTZONE))
				.orElse(DEFAULT_MESSAGE);

		logger.info(format, objects);
		
	}
	
	
}
